var guiCode = require('../../utils/guiCode.js');
const app = getApp()

Page({
  data: {
    loginUser: {
      username: '',
      password: '',
      role: '',
    },
    guiCode: '',
    isUsernameVisable: false,
    isPasswordVisable: false,
    avatar: '/static/avatar/avatar_male.jpg',
  },
  onShow: function (options) {
    this.guiCode = new guiCode({
      el: '#guiCodeCanvas',
      width: 70,
      height: 50,
      createCodeImg: ""
    });
    console.log("code==>" + this.guiCode);
  },

  /**
   * 刷新图形验证码
   */
  guiCodeTap() {
    this.guiCode.refresh();
  },

  inputUsername: function (e) {
    this.setData({
      'loginUser.username': e.detail.value
    });
  },
  inputPassword: function (e) {
    this.setData({
      'loginUser.password': e.detail.value
    });
  },

  // 选择角色
  selectRole(e) {
    // console.log("role==>" + e.detail.value);
    this.setData({
      'loginUser.role': e.detail.value
    });
  },

  /**
   * 验证用户名，密码，角色，图形验证码
   */
  toLogin() {
    console.log("username==>", this.data.loginUser.username);
    if (!this.data.loginUser.username) {
      this.setData({
        isUsernameVisable: true
      });
      return;
    }
    if (!this.data.loginUser.password) {
      this.setData({
        isPasswordVisable: true,
        isUsernameVisable: false
      });
      return;
    }
    this.setData({
      isPasswordVisable: false,
      isUsernameVisable: false
    });
    if (!this.data.loginUser.role) {
      wx.showToast({
        title: '请选择角色',
        icon: 'none'
      });
      return
    }
    if (!this.data.guiCode) {
      wx.showToast({
        title: '请输入图形验证码',
        icon: 'none'
      })
      return
    }
    let res = this.guiCode.validate(this.data.guiCode)
    if (!res) {
      wx.showToast({
        title: '图形验证码错误',
        icon: 'error'
      })
    }
    let loginUser = this.data.loginUser;
    //开始登录
    wx.request({
      url: 'http://localhost:8282/public/login',
      method: 'POST',
      data: {
        username: loginUser.username,
        password: loginUser.password,
        role: loginUser.role
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: (res) => {
        console.log("res==>", res.data);
        if (res.data.code == 200) {
          wx.setStorageSync('loginUser', res.data.data);
          wx.setStorageSync('isLogin', true);
          wx.switchTab({
            url: '/pages/index/index'
          })
        }
      },
      fail: (err) => {
        console.log(err);
        wx.showToast({
          title: '登录接口调用失败',
          icon: 'error'
        })
      }
    })
  },

  /**
   * 立即验证按钮监听
   */
  toValidate() {
    //验证图形验证码
    this.validateGuiCode()
  },

})